<?php


namespace App\Dao;


use App\Model\AdminMenu;

class AdminMenuDao extends AbstractDao
{

    /**
     * @param array $where
     * @return \Hyperf\Database\Concerns\BuildsQueries|\Hyperf\Database\Model\Builder|mixed
     */
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        return AdminMenu::query()
            ->when(
                $where['id'],
                function (\Hyperf\Database\Model\Builder $query, array $ids) {
                    return $query->whereIn('id', $ids);
                }
            );
    }

    public function getMenuTree($where)
    {
        $menus = $this->select($where);
        return $this->tree($menus);
    }

    public function tree($menus,$pid = 0)
    {
        $tree = [];
        /** @var AdminMenu $menu */
        foreach ($menus as $menu) {
            if ($menu->pid == $pid) {
                $node = [];
                $node['id'] = $menu->id;
                $node['name'] = $menu->name;
                $node['title'] = $menu->title;
                $node['api'] = $menu->api;
                $node['type'] = $menu->type;
                $node['pid'] = $pid;
                $children = $this->tree($menus, $node['id']);
                if (!empty($children)) {
                    $node['children'] = $children;
                }
                $tree[] = $node;
            }
        }
        return $tree;
    }
}